package com.qire.manhua.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qire.antscore.annotation.RouteMapping;
import com.qire.antsrouter.inject.Autowired;
import com.qire.common.constant.CustomEvent;
import com.qire.common.inject.EventControllerInjector;
import com.qire.common.utils.NoticeEventBus;
import com.qire.manhua.R;
import com.qire.common.constant.Navigation;
import com.qire.common.support.base.BaseFragment;
import com.qire.manhua.controller.BookshelfController;
import com.qire.manhua.databinding.FragmentBookshelfBinding;
import com.qire.manhua.model.enumeration.PageTabIndex;
import com.qire.manhua.model.viewModel.impl.BookshelfViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 首页->书架
 */
@RouteMapping(path = Navigation.Fragment.BookshelfFragment)
public class BookshelfFragment extends BaseFragment<FragmentBookshelfBinding> {

    @Autowired
    int pageNo = PageTabIndex.TAB_INDEX_BOOKSHELF_FAVORITES;

    @Autowired
    BookshelfViewModel viewModel;

    @Autowired(injector = EventControllerInjector.class)
    BookshelfController controller;

    @Override
    public int layoutRid() {
        return R.layout.fragment_bookshelf;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        registerObserver();
        FragmentBookshelfBinding binder = viewDataBinder(inflater,container);
        binder.setBookshelfViewModel(viewModel);

        viewModel.onAddition(this, pageNo);
        controller.onAddition(viewModel);

        return binder.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterObserver();
    }

    @Override
    protected void onLeave() {
        super.onLeave();
        // 离开选项卡页面
        viewModel.closeEditMode();
    }

    @Override
    protected void onReEnter() {
        super.onReEnter();
        // 回到选项卡页面
        togglePageIfNeed();
    }

    private void togglePageIfNeed() {
        // NOTE: 跳转页面后重置选项卡索引，避免重复进入，仅在第一次或其他页面跳转时注入索引才触发跳转子页
        if(pageNo != PageTabIndex.TAB_INDEX_INVALID) {
            viewModel.gotoPageNo(pageNo);
            pageNo = PageTabIndex.TAB_INDEX_INVALID;
        }
    }

    protected void registerObserver() {
        NoticeEventBus.NOTICE.subscribeEvent(CustomEvent.LOGIN_SUCCESS, loginSuccessHandle);
    }

    protected void unregisterObserver() {
        NoticeEventBus.NOTICE.unSubscribeEvent(loginSuccessHandle);
    }

    private NoticeEventBus.EventSubscriber loginSuccessHandle = noticeEvent -> {
        viewModel.refreshVisibleSubPage();
        return false;
    };
}
